package tools

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"

	"techoiceness.com/aiagent/llm-gateway/internal/llm/types"
)

// HTTPClientTool HTTP客户端工具
type HTTPClientTool struct {
}

// NewHTTPClientTool 创建HTTP客户端工具
func NewHTTPClientTool() *HTTPClientTool {
	return &HTTPClientTool{}
}

func (h *HTTPClientTool) Name() string {
	return "http_client"
}

func (h *HTTPClientTool) Description() string {
	return "Send HTTP requests to external APIs"
}

func (h *HTTPClientTool) Definition() types.Tool {
	return types.Tool{
		Type: "function",
		ToolFunction: types.ToolFunction{
			Name:        h.Name(),
			Description: h.Description(),
			Parameters: types.JSONSchema{
				Type: "object",
				Properties: map[string]*types.JSONSchema{
					"method": {
						Type:        "string",
						Description: "HTTP method (GET, POST, PUT, DELETE)",
						Enum:        []interface{}{"GET", "POST", "PUT", "DELETE"},
					},
					"url": {
						Type:        "string",
						Description: "The URL to send the request to",
					},
					"headers": {
						Type:        "object",
						Description: "HTTP headers to include",
					},
					"body": {
						Type:        "string",
						Description: "Request body (for POST/PUT requests)",
					},
				},
				Required: []string{"method", "url"},
			},
		},
	}
}

func (h *HTTPClientTool) Execute(arguments string) (string, error) {
	var params struct {
		Method  string            `json:"method"`
		URL     string            `json:"url"`
		Headers map[string]string `json:"headers"`
		Body    string            `json:"body"`
	}

	if err := json.Unmarshal([]byte(arguments), &params); err != nil {
		return "", fmt.Errorf("invalid arguments: %w", err)
	}

	// 创建HTTP请求
	var reqBody strings.Reader
	if params.Body != "" {
		reqBody = *strings.NewReader(params.Body)
	}

	req, err := http.NewRequest(params.Method, params.URL, &reqBody)
	if err != nil {
		return "", fmt.Errorf("failed to create request: %w", err)
	}

	// 设置头部
	for key, value := range params.Headers {
		req.Header.Set(key, value)
	}

	// 执行请求
	client := &http.Client{Timeout: 30 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		return "", fmt.Errorf("request failed: %w", err)
	}
	defer resp.Body.Close()

	// 读取响应
	body := make([]byte, 1024*1024) // 限制1MB
	n, _ := resp.Body.Read(body)

	result := map[string]interface{}{
		"status_code": resp.StatusCode,
		"headers":     resp.Header,
		"body":        string(body[:n]),
	}

	resultJSON, _ := json.Marshal(result)
	return string(resultJSON), nil
}
